<template>
<el-dialog v-model="dialogVisible" :title="formData.id ? '编辑' : '新增'" width="500" :before-close="changeDialogVisible">
  <el-form
    ref="formEl"
    style="max-width: 600px"
    :model="formData"
    label-width="auto"
    class="demo-ruleForm"
  >
    <el-form-item label="分组名称" prop="name" :rules="[{required: true, message: '请输入分组名称', trigger: 'blur'}]">
      <el-input v-model="formData.name" type="text" placeholder="请输入名称" clearable/>
    </el-form-item>
    <el-form-item label="备注" prop="remark">
      <el-input v-model="formData.remark" type="text" placeholder="请输入备注" clearable/>
    </el-form-item>
  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="changeDialogVisible(false)">取消</el-button>
      <el-button type="primary" @click="submit" :loading="loading">
        确定
      </el-button>
    </div>
  </template>
</el-dialog>
</template>


<script setup>
import { addRow } from "@/api/equipmentManagement/numberManage/grouping.api";
import useToggle from "@/hooks/useToggle";
const [loading, _, setLoading] = useToggle();
const [dialogVisible, changeDialogVisible, setDialogVisible] = useToggle();

const emit = defineEmits(["refresh"]);

const formData = ref({
  app: "VIBER",
  name: "",
  successAllowedMax: 0, // 0代表不限制
  remark: void undefined,
})

const formEl = ref(null);
const submit = async () => {
  setLoading(true);
  await formEl.value.validate((valid, fields) => {
    if (valid) {
      addRow(formData.value).then((res) => {
        ElMessage.success("添加成功");
        setLoading(false);
        setDialogVisible(false);

        emit("refresh");
      }).finally(() => {
        setLoading(false);
        setDialogVisible(false);
      })
    } else {
      console.log('error submit!', fields)
    }
  })
  
};

const handleOpen = (row) => {
  setDialogVisible(true);
  nextTick(() => {
    resetForm(formEl.value);
    row.id && (formData.value = { ...row, app: "VIBER" })
  })
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}


defineExpose({
  handleOpen,
})
</script>

